package com.atguigu.srb.oss.Service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.Service.FileService;
import com.atguigu.srb.oss.util.OssProperties;
import org.apache.ibatis.annotations.Param;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.Key;
import java.util.UUID;

/**
 * @program: srb
 * @author: 龙龙
 * @create: 2022-02-11 10:22
 * @description:
 **/
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile multipartFile , String model) {
        //阿里云绝对路径
        String url = "https://"  + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" ;

        //创建oss链接
        OSS client =   new OSSClientBuilder().build(OssProperties.ENDPOINT,OssProperties.KEY_ID,OssProperties.KEY_SECRET);

        String ext = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
        //定义路径规则 桶名.节点名/模块名/日期/随机字符串.扩展名
       String  Key =model + "/" + new DateTime().toString("yyyy/MM/dd") + UUID.randomUUID().toString() + "." + ext;

        //上传文件
        boolean b = client.doesBucketExist(OssProperties.BUCKET_NAME);
        if (!b){
            client.createBucket(OssProperties.BUCKET_NAME);
            client.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }
        try {
            client.putObject(OssProperties.BUCKET_NAME,Key,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //关闭链接
        // 关闭OSSClient。
        client.shutdown();

        //返回访问url

        return url + Key;
    }

    @Override
    public void removeFile(String url) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);

        int i = url.indexOf(".com/");
        String substring = url.substring(i + 5);
        try {
            substring = URLDecoder.decode(substring, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 删除文件。
        ossClient.deleteObject(OssProperties.BUCKET_NAME, substring);

        // 关闭OSSClient。
        ossClient.shutdown();

    }

    public static void main(String[] args) {
       String url = "https://srb0924.oss-cn-shenzhen.aliyuncs.com/海绵标标/2022/02/11a9a99f7d-589e-46c0-aafb-504fd3c6e441.jpg";
        int i = url.indexOf(".com/");
        String substring = url.substring(i + 5);
        System.out.println(substring);
    }


}








